package notification

import (
	"context"
	"encoding/json"
	"yunzhan/alert-server/internal/svc"
	"yunzhan/alert-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateNotificationLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewCreateNotificationLogic 新增通知
func NewCreateNotificationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateNotificationLogic {
	return &CreateNotificationLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateNotificationLogic) CreateNotification(req *types.CreateNotificationRequest) (resp *types.CreateNotificationResponse, err error) {

	resp = &types.CreateNotificationResponse{
		CreatedNotifications: []*types.Notification{},
	}

	// 循环处理每个通知请求
	for _, notificationReq := range req.Notifications {
		// 序列化 Config 字段为 JSON 字符串
		configBytes, err := json.Marshal(notificationReq.Config)
		if err != nil {
			logx.Errorf("Failed to marshal config for notification type: %s, error: %v", notificationReq.Type, err)
			return &types.CreateNotificationResponse{
				Success: 500,
				Message: "解析通知配置失败",
				Error:   err.Error(),
			}, err
		}

		// 创建新的通知记录
		newNotification := &types.Notification{
			Name:   notificationReq.Name,
			Type:   notificationReq.Type,
			Config: string(configBytes),
		}

		// 插入通知记录到数据库
		result, err := l.svcCtx.NotificationModel.Insert(newNotification)
		if err != nil {
			logx.Errorf("Failed to insert notification record for type: %s, error: %v", notificationReq.Type, err)
			resp.Success = 500
			resp.Message = "创建通知失败"
			resp.Error = err.Error()
			return resp, err
		}

		// 获取插入记录的ID
		id, err := result.LastInsertId()
		if err != nil {
			logx.Errorf("Failed to get last insert ID for notification type: %s, error: %v", notificationReq.Type, err)
			resp.Success = 500
			resp.Message = "获取通知ID失败"
			resp.Error = err.Error()
			return resp, err
		}

		// 设置通知ID并添加到已创建的通知列表
		newNotification.ID = id
		resp.CreatedNotifications = append(resp.CreatedNotifications, newNotification)

		logx.Infof("Successfully created notification, ID: %d, Type: %s", id, newNotification.Type)
	}

	// 设置响应的成功状态和消息
	resp.Success = 200
	resp.Message = "通知配置创建成功"

	// 返回响应对象
	return resp, nil
}
